#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <string>
#include <unordered_map>
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;

int main()
{
	IOS;
	int T=1;
	cin>>T;
	while(T--)
	{
		ll l,r;
		cin>>l>>r;
		vector<int> a;
		vector<int> b;
		while(l)
		{
			a.push_back(l%3);
			l/=3ll;
		}
		while(r)
		{
			b.push_back(r%3);
			r/=3;
		}
		int f=0;
		if(a.size()<b.size())
		{
		    f=1;
			for(int i=a.size();i<b.size();i++)
			{
				a.push_back(0);
			}
		}
		int ans=0; 
		int sum=0;
		int cnt=0;
		for(int i=a.size()-1;i>=0;i--)
		{
			if(a[i]==b[i])
			{
				ans+=a[i];
			}
			else
			{
			    if(f==0)
			    {
			        sum=max(sum,ans+b[i]-1+(i)*2+(int)a.size());
			    }
				else if(f==1)
				{
				    int t=0;
				    if(b[i]==2) t=1;
				    sum=max(sum,ans+b[i]-1+(int)(i)*2+i+t);
				    f=2;
				    cnt=i+1;
				}
				else if(f==2)
				{
				    sum=max(sum,ans+b[i]-1+(i)*2+cnt);
				}
				ans+=b[i];
			}
		}
		cout<<max(ans+(int)b.size(),sum)<<'\n';
	}
	return 0;
}
